<!-- 公司详情页面视图 - 展示单个公司的详细信息和编辑功能 -->
<template>
  <div class="company-content">
    
    <!-- 公司选择区域 -->
    <div class="company-selector">
      <button class="start-management-btn" @click="handleStartManagement">
      开始管理
      </button>
      <div class="selector-header">
        <h2>选择公司</h2>
      </div>
      <div class="company-dropdown" @click="toggleDropdown">
        <div class="selected-company">
          <span v-if="selectedCompany">{{ selectedCompany.name }}</span>
          <span v-else class="placeholder">请选择公司</span>
          <span class="dropdown-arrow">{{ isDropdownOpen ? '▲' : '▼' }}</span>
        </div>
        <div v-if="isDropdownOpen" class="company-list">
          <div v-if="loading" class="loading">加载中...</div>
          <div v-else-if="error" class="error">{{ error }}</div>
          <div v-else-if="companyList.length === 0" class="no-data">暂无公司数据</div>
          <div v-else>
            <div 
              v-for="company in companyList" 
              :key="company.id" 
              class="company-item"
              :class="{ active: selectedCompany?.id === company.id }"
              @click="selectCompany(company)"
            >
              {{ company.name }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建公司卡片 -->
    <div class="create-company-card" @click="openCreateModal">
      <div class="card-icon">➕</div>
      <h3>创建新公司</h3>
      <p>点击创建属于你的公司</p>
    </div>

    <main class="company-main">
      <div class="feature-grid">
        <div class="feature-card" @click="handleFinancialReport">
          <div class="card-icon">📊</div>
          <h3>财务报表</h3>
          <p>生成和分析财务报表</p>
        </div>

        <div class="feature-card" @click="handleCompanyAnalysis">
          <div class="card-icon">🏢</div>
          <h3>公司分析</h3>
          <p>公司运营数据分析</p>
        </div>

        <div class="feature-card" @click="handleDataImport">
          <div class="card-icon">📥</div>
          <h3>数据导入</h3>
          <p>导入财务数据</p>
        </div>

        <div class="feature-card" @click="handleSettings">
          <div class="card-icon">⚙️</div>
          <h3>设置</h3>
          <p>公司信息管理</p>
        </div>
      </div>
    </main>

    <!-- 创建公司模态框 -->
    <div v-if="isCreateModalOpen" class="modal-overlay" @click="closeCreateModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>创建新公司</h3>
          <button class="close-btn" @click="closeCreateModal">×</button>
        </div>
        <div class="modal-body">
          <!-- 创建公司表单 -->
          <form @submit.prevent="handleCreateCompany" class="company-form">
            <div class="form-group">
              <label for="company-name">公司名称 *</label>
              <input 
                type="text" 
                id="company-name" 
                v-model="companyForm.name" 
                required 
                placeholder="请输入公司名称"
              />
            </div>
            <div class="form-row">
              <div class="form-group">
                <label for="legal-person">法定代表人</label>
                <input 
                  type="text" 
                  id="legal-person" 
                  v-model="companyForm.legal_person" 
                  placeholder="请输入法定代表人姓名"
                />
              </div>
              <div class="form-group">
                <label for="industry">行业</label>
                <input 
                  type="text" 
                  id="industry" 
                  v-model="companyForm.industry" 
                  placeholder="请输入公司所属行业"
                />
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label for="registration-number">注册号</label>
                <input 
                  type="text" 
                  id="registration-number" 
                  v-model="companyForm.registration_number" 
                  placeholder="请输入工商注册号"
                />
              </div>
              <div class="form-group">
                <label for="registered-capital">注册资本</label>
                <input 
                  type="text" 
                  id="registered-capital" 
                  v-model="companyForm.registered_capital" 
                  placeholder="请输入注册资本"
                />
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label for="registration-date">注册日期</label>
                <input 
                  type="date" 
                  id="registration-date" 
                  v-model="companyForm.registration_date"
                />
              </div>
              <div class="form-group">
                <label for="contact-phone">联系电话</label>
                <input 
                  type="tel" 
                  id="contact-phone" 
                  v-model="companyForm.contact_phone" 
                  placeholder="请输入联系电话"
                />
              </div>
            </div>
            <div class="form-group">
              <label for="contact-email">联系邮箱</label>
              <input 
                type="email" 
                id="contact-email" 
                v-model="companyForm.contact_email" 
                placeholder="请输入联系邮箱"
              />
            </div>
            
            <!-- 错误和成功提示 -->
            <div v-if="submitError" class="form-error">{{ submitError }}</div>
            <div v-if="submitSuccess" class="form-success">{{ submitSuccess }}</div>
            
            <div class="form-actions">
              <button type="button" @click="closeCreateModal" :disabled="isSubmitting">取消</button>
              <button type="submit" :disabled="isSubmitting || !companyForm.name">
                {{ isSubmitting ? '创建中...' : '创建公司' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 消息提示组件 -->
  <MessageToast
    v-if="showToast"
    v-model:visible="showToast"
    :message="toastMessage"
    :type="toastType"
    :duration="3000"
  />
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCompanyStore } from '../../store/company'
import { fetchCompanies, createCompany } from '../../api/company'
import type { Company, CreateCompanyPayload } from '../../api/company'
import MessageToast from '../../components/common/MessageToast.vue'

// 路由实例
const router = useRouter()

// 获取公司状态管理实例
const companyStore = useCompanyStore()

// 响应式数据
const isDropdownOpen = ref(false)
const selectedCompany = ref(companyStore.getSelectedCompany())

// MessageToast实例管理
const showToast = ref(false)
const toastMessage = ref('')
const toastType = ref<'success' | 'warning' | 'error' | 'info'>('info')

// 显示消息提示的方法
const showMessage = (message: string, type: 'success' | 'warning' | 'error' | 'info' = 'info', duration = 3000) => {
  toastMessage.value = message
  toastType.value = type
  showToast.value = true
  
  // 300毫秒后隐藏，给动画留出时间
  setTimeout(() => {
    showToast.value = false
  }, duration)
}

// 公司列表数据
const companyList = ref<Company[]>([])
const loading = ref(false)
const error = ref('')

// 创建公司模态框相关
const isCreateModalOpen = ref(false)
const isSubmitting = ref(false)
const submitError = ref('')
const submitSuccess = ref('')

// 公司表单数据
const companyForm = ref<CreateCompanyPayload>({
  name: '',
  legal_person: '',
  registration_number: '',
  industry: '',
  registered_capital: '',
  registration_date: '',
  contact_phone: '',
  contact_email: ''
})

// 切换下拉菜单显示状态
const toggleDropdown = () => {
  isDropdownOpen.value = !isDropdownOpen.value
}

// 选择公司
const selectCompany = (company: any) => {
  selectedCompany.value = company
  // 更新store中的选中公司并保存到本地存储
  companyStore.setSelectedCompany(company)
  isDropdownOpen.value = false
}

// 点击外部关闭下拉菜单
const handleClickOutside = (event: MouseEvent) => {
  const dropdown = document.querySelector('.company-dropdown')
  if (dropdown && !dropdown.contains(event.target as Node)) {
    isDropdownOpen.value = false
  }
}

// 获取公司列表数据
const loadCompanyList = async () => {
  loading.value = true
  error.value = ''
  try {
    const response = await fetchCompanies()
    if (response.success && response.data) {
      companyList.value = response.data
      // 更新store中的公司列表
      companyStore.setCompanyList(response.data)
    }
  } catch (err) {
    console.error('获取公司列表失败:', err)
    error.value = '获取公司列表失败，请稍后重试'
    
    // 使用备用数据，确保功能可用
    const fallbackCompanies = [
      { id: 1, name: '科技有限公司A' },
      { id: 2, name: '贸易公司B' },
      { id: 3, name: '金融服务公司C' },
      { id: 4, name: '制造企业D' },
      { id: 5, name: '咨询公司E' }
    ]
    companyList.value = fallbackCompanies
    companyStore.setCompanyList(fallbackCompanies)
  } finally {
    loading.value = false
  }
}

// 组件挂载时的操作
onMounted(() => {
  // 获取公司列表数据
  loadCompanyList()
  
  // 尝试从本地存储恢复选中的公司
  const savedCompany = companyStore.getSelectedCompany()
  if (savedCompany) {
    selectedCompany.value = savedCompany
  }
  
  // 监听点击外部事件
  document.addEventListener('click', handleClickOutside)
  
  // 为了测试MessageToast组件，可以取消下面一行的注释
  // 它会在页面加载时显示一条测试消息
  // showMessage('测试消息：MessageToast组件已正确集成', 'success')
})

// 打开创建公司模态框
const openCreateModal = () => {
  isCreateModalOpen.value = true
  submitError.value = ''
  submitSuccess.value = ''
}

// 关闭创建公司模态框
const closeCreateModal = () => {
  isCreateModalOpen.value = false
  // 重置表单
  resetForm()
}

// 重置表单
const resetForm = () => {
  companyForm.value = {
    name: '',
    legal_person: '',
    registration_number: '',
    industry: '',
    registered_capital: '',
    registration_date: '',
    contact_phone: '',
    contact_email: ''
  }
  submitError.value = ''
  submitSuccess.value = ''
}

// 处理开始管理按钮点击
const handleStartManagement = () => {
  if (!selectedCompany.value) {
    showMessage('请先选择公司', 'warning')
    return
  }
  // 跳转到部门管理页面
  router.push('/company/departments')
}

// 处理创建公司表单提交
const handleCreateCompany = async () => {
  if (!companyForm.value.name) {
    submitError.value = '请输入公司名称'
    return
  }
  
  isSubmitting.value = true
  submitError.value = ''
  submitSuccess.value = ''
  
  try {
    // 过滤掉空值字段，避免发送不必要的数据
    // 确保name字段存在且不为空
    if (!companyForm.value.name) {
      throw new Error('公司名称不能为空')
    }
    
    const filteredData: Partial<CreateCompanyPayload> = Object.fromEntries(
      Object.entries(companyForm.value)
        .filter(([_, value]) => value !== '' && value !== null && value !== undefined)
    )
    
    // 调用创建公司API
    // 使用类型断言，因为我们已经确认name字段存在且不为空
    const response = await createCompany(filteredData as CreateCompanyPayload)
    
    if (response.success && response.data) {
      // 创建成功
      submitSuccess.value = '公司创建成功！'
      
      // 更新公司列表，将新创建的公司添加到列表中
      companyList.value.unshift(response.data)
      
      // 更新状态管理中的公司列表
      companyStore.setCompanyList(companyList.value)
      
      // 自动选择新创建的公司
      selectedCompany.value = response.data
      companyStore.setSelectedCompany(response.data)
      
      // 2秒后关闭模态框并重置表单
      setTimeout(() => {
        closeCreateModal()
      }, 2000)
    } else {
      submitError.value = '创建公司失败，请稍后重试'
    }
  } catch (err) {
    console.error('创建公司失败:', err)
    // 处理不同类型的错误
    if (err instanceof Error) {
      submitError.value = `创建失败: ${err.message}`
    } else {
      submitError.value = '创建公司时发生错误，请检查网络连接或稍后重试'
    }
  } finally {
    isSubmitting.value = false
  }
}

// 财务报表功能
const handleFinancialReport = () => {
  console.log('跳转到财务报表页面')
  // router.push('/company/financial-report')
}

// 公司分析功能
const handleCompanyAnalysis = () => {
  console.log('跳转到公司分析页面')
  // router.push('/company/analysis')
}

// 数据导入功能
const handleDataImport = () => {
  console.log('跳转到数据导入页面')
  // router.push('/company/data-import')
}

// 设置功能
const handleSettings = () => {
  console.log('跳转到公司设置页面')
  // router.push('/company/settings')
}
</script>

<style scoped>
.company-content {
  height: 100%;
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
  
  position: relative;
}

.start-management-btn {
  
  top: 20px;
  right: 20px;
  padding: 10px 24px;
  background-color: #667eea;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  z-index: 100;
}

.start-management-btn:hover {
  background-color: #5a67d8;
  transform: translateY(-2px);
}

.start-management-btn:active {
  transform: translateY(0);
}

/* 响应式设计：在小屏幕上调整按钮位置 */
@media (max-width: 768px) {
  .start-management-btn {
    position: static;
    display: block;
    margin: 20px auto;
    width: fit-content;
  }
}

/* 公司选择器样式 */
.company-selector {
  max-width: 1200px;
  margin: 0 auto 30px;
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.selector-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.selector-header h2 {
  color: #333;
  font-size: 24px;
  margin: 0;
}

/* 创建公司卡片响应式设计 */
@media (max-width: 768px) {
  .create-company-card {
    padding: 20px;
    margin-bottom: 20px;
  }
  
  .create-company-card .card-icon {
    font-size: 36px;
    margin-bottom: 15px;
  }
  
  .create-company-card h3 {
    font-size: 18px;
  }
  
  .create-company-card p {
    font-size: 13px;
  }
}

.company-dropdown {
  position: relative;
  width: 300px;
}

.selected-company {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.selected-company:hover {
  border-color: #667eea;
}

.selected-company .placeholder {
  color: #909399;
}

.dropdown-arrow {
  color: #606266;
  font-size: 12px;
  transition: transform 0.3s;
}

.company-list {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-top: 5px;
  max-height: 200px;
  overflow-y: auto;
  z-index: 1000;
}

.company-item {
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.company-item:hover {
  background-color: #f5f7fa;
}

.company-item.active {
  background-color: #ecf5ff;
  color: #667eea;
}

.loading {
  padding: 12px 16px;
  color: #606266;
  text-align: center;
}

.error {
  padding: 12px 16px;
  color: #f56c6c;
  text-align: center;
}

.no-data {
  padding: 12px 16px;
  color: #909399;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .company-dropdown {
    width: 100%;
  }
  
  .selector-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .create-company-btn {
    align-self: flex-start;
  }
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.15);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.modal-header h3 {
  margin: 0;
  color: #333;
  font-size: 20px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #909399;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s;
}

.close-btn:hover {
  background-color: #f5f7fa;
  color: #606266;
}

.modal-body {
  padding: 20px;
}

/* 表单样式 */
.company-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-row {
  display: flex;
  gap: 16px;
}

.form-group {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-group label {
  font-weight: 500;
  color: #606266;
  font-size: 14px;
}

.form-group input {
  padding: 10px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-group input:focus {
  outline: none;
  border-color: #667eea;
}

.form-group input::placeholder {
  color: #c0c4cc;
}

/* 错误和成功提示样式 */
.form-error {
  color: #f56c6c;
  font-size: 14px;
  padding: 8px 12px;
  background-color: #fef0f0;
  border: 1px solid #fbc4c4;
  border-radius: 6px;
  margin-top: 8px;
}

.form-success {
  color: #67c23a;
  font-size: 14px;
  padding: 8px 12px;
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
  border-radius: 6px;
  margin-top: 8px;
}

/* 表单操作按钮样式 */
.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.form-actions button {
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.form-actions button[type="button"] {
  background-color: #f5f7fa;
  color: #606266;
  border: 1px solid #dcdfe6;
}

.form-actions button[type="button"]:hover:not(:disabled) {
  background-color: #e6e8eb;
}

.form-actions button[type="submit"] {
  background-color: #667eea;
  color: white;
  border: none;
}

.form-actions button[type="submit"]:hover:not(:disabled) {
  background-color: #5a67d8;
}

.form-actions button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 响应式表单样式 */
@media (max-width: 600px) {
  .form-row {
    flex-direction: column;
  }
  
  .modal-content {
    width: 95%;
    margin: 20px;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .form-actions button {
    width: 100%;
  }
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 8px 16px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.back-btn:hover {
  background: #5a67d8;
}

.back-icon {
  font-size: 16px;
}

.company-header h1 {
  color: #333;
  font-size: 32px;
  margin-bottom: 10px;
}

.company-header p {
  color: #666;
  font-size: 16px;
}

.create-company-card {
  max-width: 1200px;
  margin: 0 auto 30px;
  background: white;
  border-radius: 12px;
  padding: 30px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
  border: 2px dashed #e4e7ed;
}

.create-company-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  border-color: #667eea;
  background-color: #f8f9ff;
}

.create-company-card .card-icon {
  font-size: 48px;
  margin-bottom: 20px;
  color: #667eea;
}

.create-company-card h3 {
  color: #333;
  font-size: 20px;
  margin-bottom: 10px;
}

.create-company-card p {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

.company-main {
  max-width: 1200px;
  margin: 0 auto;
}

.feature-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
}

.feature-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
}

.feature-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.card-icon {
  font-size: 48px;
  margin-bottom: 20px;
}

.feature-card h3 {
  color: #333;
  font-size: 20px;
  margin-bottom: 10px;
}

.feature-card p {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .company-header h1 {
    font-size: 24px;
  }
  
  .feature-grid {
    grid-template-columns: 1fr;
  }
  
  .feature-card {
    padding: 20px;
  }
}
</style>